package com.easy.leetcode;

import java.util.Objects;

/**
 * @ClassName StrStr28
 * @Description 28. 实现 strStr()
 * @Author zheng
 * @Date 2021/10/27 21:19
 * @Version 1.0
 **/
public class StrStr28 {
    public int strStr(String haystack, String needle) {
        if (Objects.equals(needle, "")) {
            return 0;
        }
        for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
            for (int j = 0; j < needle.length(); j++) {
                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    break;
                }
                if (j == needle.length() - 1) {
                    return i;
                }
            }
        }
        return -1;
    }

    /**
     * @return int[]
     * @Description next数组，
     * 数据不匹配时回溯的位置
     * @Date 2021/10/29 11:27
     * @Param [needle]
     **/
    public int[] getNext(String needle) {
        int[] next = new int[needle.length()];
        //最长相等前后缀长度，同样是前缀的开始位置
        int j = 0;
        next[0] = 0;
        for (int i = 1; i < needle.length(); i++) {
            while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            //相等
            if (needle.charAt(i) == needle.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

    public int kmp(String haystack, String needle) {
        if (needle.length() == 0) {
            return 0;
        }
        int[] next = getNext(needle);
        int j = 0;
        for (int i = 0; i < haystack.length(); i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            if (haystack.charAt(i) == needle.charAt(j)) {
                j++;
            }
            if (j == needle.length()) {
                return i - needle.length() + 1;
            }
        }
        return -1;
    }
}
